package com.car.dao.impl;

import com.car.dao.UserDao;
import com.car.domain.Car;
import com.car.domain.User;
import com.car.utils.JDBCUtil;

import java.util.List;

/**
 * UserDao的实现类
 */
public class UserDaoImpl implements UserDao {
    /**
     * 新增
     *
     * @param user 泛型
     */
    @Override
    public int add(User user) throws Exception {
        String sql = "insert into t_user (name, password, phone, email) \n" +
                "VALUE(?,?,?,?)";
        return JDBCUtil.update(sql, user.getName(), user.getPassword(), user.getPhone(), user.getEmail());
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return 影响记录数
     */
    @Override
    public int delete(int id) throws Exception {
        String sql = "delete from t_user where id = ? ";
        return JDBCUtil.update(sql, id);
    }

    /**
     * 修改
     *
     * @param user 泛型
     */
    @Override
    public int update(User user) throws Exception {
        String sql = "update t_user set name = ?,password=?,phone=?,email=? " +
                "where id = ?";
        return JDBCUtil.update(sql, user.getName(), user.getPassword(), user.getPhone()
                , user.getEmail(), user.getId());
    }

    /**
     * 通过主键id查询
     *
     * @param id 主键id
     * @return 实体类
     */
    @Override
    public User queryById(int id) throws Exception {
        String sql = "select * from t_user where id = ?";
        return JDBCUtil.query(sql, User.class, id);
    }

    /**
     * 查询所有记录
     *
     * @return 实体类集合
     */
    @Override
    public List<User> queryAll() throws Exception {
        String sql = "select * from t_user";
        return JDBCUtil.queryList(sql, User.class);
    }

    @Override
    public User findByPhone(String phone) throws Exception {
        String sql = "select * from t_user where phone = ?";
        return JDBCUtil.query(sql, User.class, phone);
    }

    @Override
    public User login(String phone, String password) throws Exception {
        String sql = "select * from t_user where phone = ? and password =?";
        return JDBCUtil.query(sql, User.class, phone, password);
    }

    @Override
    public List<Car> findUserCarsById(Integer userId) throws Exception {
        String sql = "select tc.* from t_user_car tuc left join t_car tc " +
                "on tuc.car_id = tc.id where tuc.user_id = ?";
        return JDBCUtil.queryList(sql, Car.class, userId);
    }
}
